package com.jzo2o.foundations.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.*;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeAggregationSimpleResDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.*;
import com.jzo2o.mysql.utils.PageHelperUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 区域服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-03
 */
@Service
@Slf4j
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Resource
    private IServeItemService serveItemService;

    @Resource
    private IServeTypeService serveTypeService;

    @Resource
    private RegionMapper regionMapper;

    @Resource
    private HomeService homeService;

    @Resource
    private IServeSyncService serveSyncService;

    /**
     * 区域服务分页查询
     *
     * @param servePageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        return PageHelperUtils.selectPage(servePageQueryReqDTO, () -> baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
    }

    /**
     * 区域批量新增服务项
     *
     * @param serveUpsertReqDto
     */
    @Override
    @Transactional
    public void add(List<ServeUpsertReqDTO> serveUpsertReqDto) {
        if (ObjectUtil.isNull(serveUpsertReqDto)) {
            return;
        }
        List<Serve> serves = new ArrayList<>();
        serveUpsertReqDto.forEach(
                // 批量校验
                serveUpsertReqDTO -> {
                    ServeItem serveItem = serveItemService.getById(serveUpsertReqDTO.getServeItemId());
                    // 校验服务项目是否存在以及是否启用
                    if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
                        throw new ForbiddenOperationException("服务项异常");
                    }

                    // 校验当前区域是否存在该服务
                    Long count = lambdaQuery()
                            .eq(Serve::getRegionId, serveUpsertReqDTO.getRegionId())
                            .eq(Serve::getServeItemId, serveUpsertReqDTO.getServeItemId())
                            .count();
                    if (count > 0) {
                        throw new ForbiddenOperationException("当前区域已存在该服务");
                    }
                    // 校验完成，拷贝数据
                    Serve bean = BeanUtils.toBean(serveUpsertReqDTO, Serve.class);
                    bean.setPrice(serveItem.getReferencePrice());
                    Region region = regionMapper.selectById(serveUpsertReqDTO.getRegionId());
                    bean.setCityCode(region.getCityCode());
                    serves.add(bean);
                }
        );
        // 批量保存
        saveBatch(serves);
    }

    /**
     * 上架服务项
     *
     * @param id
     */
    @Override
    @CachePut(value = RedisConstants.CacheName.SERVE, key = "#id",
            cacheManager = RedisConstants.CacheManager.ONE_DAY)
    @Transactional
    public Serve onSale(Long id) {
        // 校验数据
        if (ObjectUtil.isNull(id)) {
            throw new ForbiddenOperationException("区域服务项id不能为空");
        }
        Serve serve = getById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() != FoundationStatusEnum.INIT.getStatus() && serve.getSaleStatus() != FoundationStatusEnum.DISABLE.getStatus()) {
            throw new ForbiddenOperationException("草稿或下架状态才可上架！");
        }

        ServeItem serveItem = serveItemService.getById(serve.getServeItemId());
        if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("仅能上架已启用的和服务项目");
        }
        serve.setSaleStatus(FoundationStatusEnum.ENABLE.getStatus());
        boolean b = updateById(serve);
        if (!b) {
            throw new ForbiddenOperationException("服务项上架失败");
        }

        // 上架完成后，同步数据给 serve_sync 表
        log.info("服务项[id={}]上架成功，开始同步数据给 serve_sync 表", serve.getId());
        ServeSync serveSync = BeanUtils.toBean(serve, ServeSync.class);
        serveSync.setServeItemName(serveItem.getName());
        serveSync.setServeTypeId(serveItem.getServeTypeId());
        serveSync.setServeItemSortNum(serveItem.getSortNum());
        ServeType serveType = serveTypeService.getById(serveItem.getServeTypeId());
        serveSync.setServeTypeSortNum(serveType.getSortNum());
        serveSync.setServeTypeName(serveType.getName());
        serveSync.setServeTypeImg(serveType.getImg());
        serveSync.setServeTypeIcon(serveType.getServeTypeIcon());
        serveSync.setUnit(serveItem.getUnit());
        serveSync.setDetailImg(serveItem.getDetailImg());
        serveSync.setServeItemImg(serveItem.getImg());
        serveSync.setServeItemIcon(serveItem.getServeItemIcon());
        boolean sync = serveSyncService.save(serveSync);
        if (!sync) {
            throw new ForbiddenOperationException("服务项同步数据失败");
        }
        log.info("服务项[id={}]同步数据成功", serve.getId());
        return serve;
    }

    /**
     * 服务项置顶
     *
     * @param id
     */
    @Override
    public void onHot(Long id) {
        if (ObjectUtil.isNull(id)) {
            throw new ForbiddenOperationException("区域服务项id不能为空");
        }
        Serve serve = getById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("仅能置顶已上架的服务项");
        }
        serve.setIsHot(1);
        serve.setHotTimeStamp(System.currentTimeMillis());
        boolean b = updateById(serve);
        if (!b) {
            throw new ForbiddenOperationException("服务项置顶失败");
        }
        // 服务项置顶完成后，同步数据给 serve_sync 表
        boolean sync = serveSyncService.lambdaUpdate()
                .eq(ServeSync::getId, serve.getId())
                .set(ServeSync::getIsHot, 1)
                .set(ServeSync::getHotTimeStamp, System.currentTimeMillis())
                .update();
        if (!sync) {
            throw new ForbiddenOperationException("服务项同步数据失败");
        }
        log.info("服务项[id={}]同步数据成功", serve.getId());
    }

    /**
     * 服务项取消置顶
     *
     * @param id
     */
    @Override
    public void offHot(Long id) {
        if (ObjectUtil.isNull(id)) {
            throw new ForbiddenOperationException("区域服务项id不能为空");
        }
        Serve serve = getById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("当前服务项不存在！");
        }
        serve.setIsHot(0);
        boolean b = updateById(serve);
        if (!b) {
            throw new ForbiddenOperationException("服务项取消置顶失败");
        }
        // 服务项取消置顶完成后，同步数据给 serve_sync 表
        boolean sync = serveSyncService.lambdaUpdate()
                .eq(ServeSync::getId, serve.getId())
                .set(ServeSync::getIsHot, 0)
                .set(ServeSync::getHotTimeStamp, null)
                .update();
        if (!sync) {
            throw new ForbiddenOperationException("服务项同步数据失败");
        }
        log.info("服务项[id={}]取消置顶成功，开始同步数据给 serve_sync 表", serve.getId());
    }

    /**
     * 服务项下架
     *
     * @param id
     */
    @Override
    @CacheEvict(value = RedisConstants.CacheName.SERVE, key = "#id")
    @Transactional
    public void offSale(Long id) {
        if (ObjectUtil.isNull(id)) {
            throw new ForbiddenOperationException("区域服务项id不能为空");
        }
        Serve serve = getById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("仅能下架已上架的服务项");
        }
        serve.setSaleStatus(FoundationStatusEnum.DISABLE.getStatus());
        boolean b = updateById(serve);
        if (!b) {
            throw new ForbiddenOperationException("服务项下架失败");
        }
        // 服务项下架完成后，同步数据给 serve_sync 表，删除 serve_sync 表中该服务项数据
        log.info("服务项[id={}]下架成功，开始同步数据给 serve_sync 表", serve.getId());
        boolean sync = serveSyncService.removeById(id);
        if (!sync) {
            throw new ForbiddenOperationException("服务项同步数据失败");
        }
        log.info("服务项[id={}]同步数据成功", serve.getId());
    }

    /**
     * 服务项删除
     *
     * @param id
     */
    @Override
    public void removeById(Long id) {
        // 校验数据
        if (ObjectUtil.isNull(id)) {
            throw new ForbiddenOperationException("区域服务项id不能为空");
        }
        Serve serve = getById(id);
        if (ObjectUtil.isNull(serve) || serve.getSaleStatus() != FoundationStatusEnum.INIT.getStatus()) {
            throw new ForbiddenOperationException("仅能删除草稿状态的服务项");
        }
        int i = baseMapper.deleteById(id);
        if (i <= 0) {
            throw new ForbiddenOperationException("服务项删除失败");
        }
    }

    /**
     * 修改服务项价格
     *
     * @param id
     * @param price
     */
    @Override
    public void updatePrice(Long id, BigDecimal price) {
        if (ObjectUtil.isNull(id)) {
            throw new ForbiddenOperationException("服务项id不能为空");
        }
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getPrice, price)
                .update();
        if (!update) {
            throw new ForbiddenOperationException("服务项价格修改失败");
        }
        log.info("服务项[id={}]价格修改成功，同步给 serve_sync", id);
        boolean sync = serveSyncService.lambdaUpdate()
                .eq(ServeSync::getId, id)
                .set(ServeSync::getPrice, price)
                .update();
        if (!sync) {
            throw new ForbiddenOperationException("服务项价格同步失败");
        }
        log.info("同步serve_sync完成");
    }

    /**
     * 服务项详情缓存
     *
     * @param id
     * @return
     */
    @Cacheable(value = RedisConstants.CacheName.SERVE, key = "#id", cacheManager = RedisConstants.CacheManager.ONE_DAY)
    public Serve queryServeByIdCache(Long id) {
        return getById(id);
    }

    /**
     * 服务项详情
     */
    @Override
    public ServeAggregationSimpleResDTO queryServeDetailCache(Long id) {
        // 查询服务信息
        Serve serve = homeService.queryServeByIdCache(id);

        // 查询服务项信息
        ServeItem serveItem = serveItemService.getById(serve.getServeItemId());

        return ServeAggregationSimpleResDTO.builder()
                .serveItemName(serveItem.getName())
                .serveItemImg(serveItem.getImg())
                .unit(serveItem.getUnit())
                .detailImg(serveItem.getDetailImg())
                .price(serve.getPrice())
                .cityCode(serve.getCityCode())
                .serveItemId(serveItem.getId())
                .build();
    }
}
